<template>
  <div>
  </div>
</template>

<script>
var map

export default {
  props: {
    ak: {
	  type: String,
	  default: ''
	},
	point_list: Array,
	lat: {
	  type: Number,
	  default: 23.1401
	},
	lon: {
	  type: Number,
	  default: 113.326387
	},
  },
  mounted() {
    if(BMap) {
	  this.initMap()
	} else {
	  window.BMap = {}
	  var cbkName = cbk + parseInt(100 * Math.random())
	  BMap[cbkName] = () => {
	    this.initMap()
		delete BMap[cbkName]
	  }
	  var script = document.createElement('script')
	  script.type = 'text/javascript'
	  script.src = 'http://api.map.baidu.com/api?v=2.0&ak=' + this.ak + '&callback=BMap.' + cbkName
	  document.body.appendChild(script)
	}
  },
  methods: {
    initMap() {
	  map = new BMap.Map(this.$el)
	  var point = new BMap.Point(this.lon, this.lat)
	  map.centerAndZoom(point, 15)
	  
	  function CenterControl() {
	    this.defaultAnchor = BMAP_ANCHOR_BOTTOM_RIGHT
	    this.defaultOffset = new BMap.Size(10, 10)
	  }
	  
	  CenterControl.prototype = new BMap.Control()
	  
	  const _this = this
	  CenterControl.prototype.initialize = (map) => {
	    var div = document.createElement('div')
	    div.innerHTML = '<i class="iconfont" style="color:#1d8fd5">&#xe659;</i>'
		div.style.width = '25px'
		div.style.height = '25px'
		div.style.textAlign = 'center'
	    div.style.border = '1px solid #1d8fd5'
	    div.style.backgroundColor = 'white'
	    div.onclick = function(e) {
		  if(_this.point_list.length > 0)
	  	    map.setCenter(new BMap.Point(_this.point_list[0].lon, _this.point_list[0].lat))
	    }
	    map.getContainer().appendChild(div)
	    return div
	  }
	  
	  map.addControl(new CenterControl())
	}
  },
  watch: {
    point_list(value) {
	  map.clearOverlays()
	  var pointList = []
	  value.forEach(item => {
	    var point = new BMap.Point(item.lon, item.lat)
		pointList.push(point)
	    var marker = new BMap.Marker(point, {
		  icon: new BMap.Icon(require('../img/map_marker.png'), new BMap.Size(25, 25))
		})
		var label = new BMap.Label(item.label, {
		  offset: new BMap.Size(20, 0)
		})
	    marker.setLabel(label)
        map.addOverlay(marker)
	  })
	  map.setViewport(pointList)
	},
	lat(value) {
	  map.setCenter(new BMap.Point(this.lon, this.lat))
	},
	lon(value) {
	  map.setCenter(new BMap.Point(this.lon, this.lat))
	}
  },
  beforeDestroy() {
    map.clearOverlays()
    map = null
  }
}
</script>